#include "internalvehicledialog.h"
#include "ui_internalvehicledialog.h"

InternalVehicleDialog::InternalVehicleDialog(QWidget* parent, EParkingSqlite* db)
    : QDialog(parent), db(db)
    , ui(new Ui::InternalVehicleDialog)
{
    ui->setupUi(this);

    // 初始化停车记录TABLE模型
    innerListModel = new QStandardItemModel(this);
    ui->tableView_innerList->setModel(innerListModel);

    // 设置停车记录TABLE属性
    ui->tableView_innerList->setSortingEnabled(true);
    ui->tableView_innerList->horizontalHeader()->setStretchLastSection(true);
    // 设置选择行为：选中整行
    ui->tableView_innerList->setSelectionBehavior(QAbstractItemView::SelectRows);
    // 设置选择模式：单选
    ui->tableView_innerList->setSelectionMode(QAbstractItemView::SingleSelection);

    //初始化日期选择框的日期为今天
    ui->dateEdit_from->setDateTime(QDateTime::currentDateTime());
    ui->dateEdit_to->setDateTime(QDateTime::currentDateTime().addYears(1));

    ui->textEdit_plate->setFocus();

    refreshInternalTable();
}

InternalVehicleDialog::~InternalVehicleDialog()
{
    delete ui;
}




// internalvehicledialog.cpp

// 刷新表格实现
void InternalVehicleDialog::refreshInternalTable()
{
    innerListModel->clear();

    // 设置中文列头
    QStringList headers = {
        "车牌号", "有效期始",
        "有效期终", "是否有效"
    };
    innerListModel->setHorizontalHeaderLabels(headers);
    // 获取所有内部车辆

    QList<QVariantMap> lists = db->getInternalCar();


    QDateTime nowDateTime = QDateTime::currentDateTime();

    // 填充数据
    for (const auto &list : lists) {
        QList<QStandardItem*> rowItems;

        // 车牌号
        rowItems << new QStandardItem(list["plate_number"].toString());

        // 时间格式化
        QDateTime valid_from = list["valid_from"].toDateTime();
        QDateTime valid_to = list["valid_to"].toDateTime();
        rowItems << new QStandardItem(valid_from.toString("yyyy-MM-dd hh:mm"));
        rowItems << new QStandardItem(valid_to.toString("yyyy-MM-dd hh:mm"));
        rowItems << new QStandardItem(QString("%1").arg(valid_to > nowDateTime? "有效":"过期"));
        // 添加行
        innerListModel->appendRow(rowItems);
    }

    // 调整列宽更好看
    QHeaderView* header = ui->tableView_innerList->horizontalHeader();
    header->resizeSection(0, 100);
    header->resizeSection(1, 150);
    header->resizeSection(2, 150);
    header->resizeSection(3, 50);
    // 在refresh函数末尾添加按ID降序排列，新的ID在前面
    innerListModel->sort(0, Qt::DescendingOrder);
    // 允许用户点击排序
    ui->tableView_innerList->setSortingEnabled(true);


}

// 添加按钮点击处理
void InternalVehicleDialog::on_pushButton_add_clicked()
{
    // 获取输入
    QString plate = ui->textEdit_plate->toPlainText().trimmed();
    QDateTime from = ui->dateEdit_from->dateTime();
    QDateTime to = ui->dateEdit_to->dateTime();

    // 车牌有效性检查（示例：简/繁中文开头+字母+·+5位数字字母组合）
    QRegularExpression plateRegExp("^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$");
    if (!plateRegExp.match(plate).hasMatch()) {
        QMessageBox::warning(this, "输入错误",
                             "车牌格式无效！\n正确示例：湘A·12345 或 浙AD23456");
        ui->textEdit_plate->setFocus();
        return;
    }

    // 日期有效性检查
    if (from >= to) {
        QMessageBox::warning(this, "日期错误", "有效期起始时间必须早于结束时间");
        return;
    }
    /*if (from < QDateTime::currentDateTime()) {
        QMessageBox::warning(this, "日期错误", "起始时间不能早于当前时间");
        return;
    }
*/
    // 检查是否已存在
    QSqlQuery checkQuery(db->getDatabase());
    checkQuery.prepare("SELECT 1 FROM internal_vehicles WHERE plate_number = ?");
    checkQuery.addBindValue(plate);
    if (checkQuery.exec() && checkQuery.next()) {
        QMessageBox::StandardButton reply = QMessageBox::question(
            this, "确认覆盖", "该车牌已存在，是否更新有效期？");
        if (reply != QMessageBox::Yes) return;
    }

    // 调用数据库操作
    if (db->addInternalVehicle(plate, from, to)) {

        QMessageBox::information(this, "成功", "车辆信息已保存");
        ui->textEdit_plate->clear();
        refreshInternalTable();
    } else {
        QMessageBox::critical(this, "错误", "保存失败，请检查数据库连接");
    }
}

// 删除按钮点击处理
void InternalVehicleDialog::on_pushButton_remove_clicked()
{

    QModelIndexList selected = ui->tableView_innerList->selectionModel()->selectedRows();

    if(selected.isEmpty()) {
        QMessageBox::warning(this,
                             "未选择车辆",
                             "请先在列表中单击选中要删除的车辆！");
        return;
    }

    int row = selected.first().row();
    qDebug() << row;
    QString plate = ui->tableView_innerList->model()->index(row, 0).data().toString();

    // 确认对话框
    QMessageBox::StandardButton reply = QMessageBox::question(
        this,
        "确认删除",
        QString("确定要删除车牌【%1】吗？").arg(plate),
        QMessageBox::Yes | QMessageBox::No
        );

    if (reply == QMessageBox::Yes) {
        if (db->removeInternalVehicle(plate)) {
            refreshInternalTable();
            ui->textEdit_plate->clear();
            QMessageBox::information(this, "成功", "车辆删除成功");
        } else {
            QMessageBox::critical(this, "错误",
                                  QString("删除失败"));
        }
    }
}
